package com.jinglvhuanjing.app.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.jinglvhuanjing.app.R;
import com.jinglvhuanjing.app.bean.LogEvent;
import com.jinglvhuanjing.app.bean.RunEvent;
import com.jinglvhuanjing.app.utils.ByteUtil;
import com.jinglvhuanjing.app.utils.LOG;
import com.jinglvhuanjing.app.utils.SerialMsgHandler;
import com.jinglvhuanjing.app.utils.SingletonSerl;
import com.jinglvhuanjing.app.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;

public class ParamSettingRow6SecView extends ConstraintLayout {

    private static final String TAG = "地址更改";

    /*** 当前地址(数字) ***/
    private CustomEdtView edt_now_address;
    /*** 目标地址(数字) ***/
    private CustomEdtView edt_to_address;
    /*** 更改地址 ***/
    private ButtonView btn_change;

    public ParamSettingRow6SecView(@NonNull Context context) {
        super(context);
        this.init(context);
    }

    public ParamSettingRow6SecView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.init(context);
    }

    public ParamSettingRow6SecView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.init(context);
    }

    /*** 解析收到的投口更改信息 ***/
    Handler mHandlerQt = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String obj = (String) msg.obj;
                    if (!StringUtils.isEmpty(obj)) {
                        byte[] bytes_ = ByteUtil.hexStringToBytes(obj);
                        if (bytes_ != null && bytes_.length > 1) {
                            // 03 功能码，轮询信息返回
                            if (bytes_[1] == SingletonSerl.byte_gnm_cssz && bytes_.length > 7) {
                                LOG.e(TAG, "读取内容:" + obj);
                                parseByte(bytes_);
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Subscribe
    public void onEvent(RunEvent event) {
        String hex = ByteUtil.hexBytesToString(event.getValue());
        LOG.e(SerialMsgHandler.TAG, TAG+"-读取内容:" + hex);
        Message message = this.mHandlerQt.obtainMessage();
        message.what = 0;
        message.obj = hex;
        this.mHandlerQt.sendMessage(message);
    }

    /**
     * @param bytes
     */
    public void parseByte(byte[] bytes) {
        LogEvent logEvent = new LogEvent();
        logEvent.setTAG(TAG);
        String jcqdz = ByteUtil.hexBytesToString(new byte[]{bytes[2], bytes[3]});
        LOG.e(TAG, "寄存器地址：" + jcqdz);
        String lx = SingletonSerl.getJCQDZLX_DZGG(jcqdz);
        LOG.e(TAG, "类型：" + lx);
        if (!"未知".equals(lx)) {
            String bw = ByteUtil.hexBytesToString(bytes);
            logEvent.setValue(
                    String.format("【%s号地址】<%s>设置%s:%s"
                            , ByteUtil.hexByteToString(bytes[5])
                            , lx
                            , "成功"
                            , StringUtils.subStringToSpace(bw, 2))
            );
            EventBus.getDefault().post(logEvent);
        }
    }

    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.view_params_setting_row_6_sec_layout, this, true);
        edt_now_address = findViewById(R.id.edt_now_address);
        edt_to_address = findViewById(R.id.edt_to_address);
        btn_change = findViewById(R.id.btn_change);

        SerialMsgHandler.getInstance().setStartListener(true, this.mHandlerQt);
        EventBus.getDefault().register(this);
        setOnClick();
    }

    public void onDestroy() {
        try {
            EventBus.getDefault().unregister(this);
        }catch (Exception e){

        }
    }

    private void setOnClick() {
        btn_change.setOnClickListener(view -> {
            String now = edt_now_address.getText().toString();
            String to = edt_to_address.getText().toString();
            if (StringUtils.isEmpty(now) || StringUtils.isEmpty(to)) {
                Toast.makeText(getContext(), "请先填入当前地址或目标地址", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    SingletonSerl singletonSerl = SingletonSerl.getInstance();
                    StringBuffer buffer = singletonSerl.changeAddress(
                            ByteUtil.String_0(ByteUtil.intToHex(Integer.valueOf(now)), 2),
                            ByteUtil.String_0(ByteUtil.intToHex(Integer.valueOf(to)), 2));
                    String bw = singletonSerl.write(TAG, buffer);
                    eventBus(ByteUtil.intToHex(Integer.valueOf(to)), "地址更改", bw);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void eventBus(String tkdz, String type, String bw) {
        LogEvent logEvent = new LogEvent();
        logEvent.setTAG(TAG);
        logEvent.setValue(
                String.format("【%s号地址】<%s>发送:%s"
                        , ByteUtil.hexStringToInt(tkdz)
                        , type
                        , StringUtils.subStringToSpace(bw, 2)));
        EventBus.getDefault().post(logEvent);
    }

}
